import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';
import 'package:signage/app/modules/cast/controllers/cast_controller.dart';
import 'package:signage/app/modules/home/controllers/home_controller.dart';
import 'package:signage/app/routes/app_pages.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/edit_dialog.dart';
import '../../../data/models/cast_record_model.dart';

class CastRecordController extends GetxController
    with GetTickerProviderStateMixin {
  final records = <CastRecord>[].obs;
  final successRecords = <CastRecord>[].obs;
  final failRecords = <CastRecord>[].obs;
  late TabController tabController;
  final currentTab = 0.obs;
  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 3, vsync: this);
   tabController.addListener(() {
      currentTab.value = tabController.index;
    });
    loadRecords();
  }

  void loadRecords() async {
    final recordStrings = SpUtil.getStringList('cast_records') ?? [];

    records.value = recordStrings
        .map((str) => CastRecord.fromJson(jsonDecode(str)))
        .toList()
      ..sort((a, b) {
        // 首先按置顶状态排序
        if (a.isPinned != b.isPinned) {
          return b.isPinned ? 1 : -1; // 置顶的排在前面
        }
        // 其次按时间倒序排序
        return b.timestamp.compareTo(a.timestamp);
      });

    successRecords.value = records.where((el) => el.success).toList();

    failRecords.value = records.where((el) => !el.success).toList();
  }

  void clearRecords() async {
    final result = await Get.dialog(
      TipsDialog(
        title: AppLocalizations.of(Get.context!)!.translate('tips'),
        text: AppLocalizations.of(Get.context!)!.translate('confirm_clear_all_records'),
        showCancel: true,
      ),
    );

    if (result == true) {
      await SpUtil.remove('cast_records');
      records.clear();
      Get.snackbar(
        '提示',
        '记录已清空',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    }
  }

  void deleteRecord(CastRecord record) async {
    final recordStrings = SpUtil.getStringList('cast_records') ?? [];

    // 找到并删除对应的记录
    recordStrings.removeWhere((str) {
      final rec = CastRecord.fromJson(jsonDecode(str));
      return rec.id == record.id; // 假设CastRecord有一个唯一的id字段
    });

    await SpUtil.setStringList('cast_records', recordStrings);
    records.remove(record);
  }

  void recastRecord(CastRecord record) {
    final castController = Get.find<CastController>();
    castController.selectedDevices.value = record.deviceInfos;
    castController.templateModelA.value = record.templateA;
    castController.templateModelB.value = record.templateB;
    castController.selectedMembers.value = record.memberInfos;
    castController.meetingTitle.value = record.meetingTitle;
    castController.sampleValue.value = record.castMode;
    castController.selectedGroupId.value = record.groupId;
    castController.selectedGroupName.value = record.groupName;
    Get.find<HomeController>().changeIndex(0);
    Get.back();
  }

  void viewRecordDetail(CastRecord record) {
    Get.toNamed(Routes.CAST_RECORD_DETAIL, arguments: record);
  }

  void togglePin(CastRecord record) async {
    final recordStrings = SpUtil.getStringList('cast_records') ?? [];

    // 找到并更新对应记录的置顶状态
    final updatedRecordStrings = recordStrings.map((str) {
      final rec = CastRecord.fromJson(jsonDecode(str));
      if (rec.id == record.id) {
        final updatedRec = rec.copyWith(isPinned: !rec.isPinned); // 保存新对象
        // 显示对应的toast消息
        Get.snackbar(
          '提示',
          updatedRec.isPinned ? '置顶成功' : '取消置顶成功',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
        return jsonEncode(updatedRec.toJson());
      }
      return str;
    }).toList();

    // 保存到 SharedPreferences
    await SpUtil.setStringList('cast_records', updatedRecordStrings);

    // 更新本地记录并重新排序
    final index = records.indexWhere((r) => r.id == record.id);
    if (index != -1) {
      // 使用新对象替换原对象
      records[index] =
          records[index].copyWith(isPinned: !records[index].isPinned);
      // 触发列表更新
      records.refresh();
      // 重新排序
      records.sort((a, b) {
        if (a.isPinned != b.isPinned) {
          return b.isPinned ? 1 : -1;
        }
        return b.timestamp.compareTo(a.timestamp);
      });
    }
  }
}
